<template>
  <div class="course-video">
     <el-card>
       <div slot="header">
         课程相关信息
       </div>
       <el-form>
         <el-form-item label="视频上传">
           <input type="file" ref="video-file">
         </el-form-item>
         <el-form-item label="封面上传">
           <input type="file" ref="img-file">
            </el-form-item>
         <el-form-item>
           <el-button type="primary" @click="handleUpload">开始上传</el-button>
           <el-button @click="$router.push({
             name: 'course-section',
             params: {
               courseId
             }
           })">返回</el-button>
         </el-form-item>
         <el-form-item>
           <p v-if="uploadPercent !== 0">视频上传中: {{uploadPercent}}%</p>
           <p v-if="isUploadSuccess">视频转码中：{{ isTransCodeSuccess ? '完成' : '正在转码中....' }}</p>
         </el-form-item>
       </el-form>
     </el-card>
  </div>
</template>

<script>
import {
  aliyunImagUploadAddressAdnAuth,
  aliyunVideoUploadAddressAdnAuth,
  aliyunTransCode,
  aliyunTransCodePercent
} from '@/services/aliyun-upload.js'

export default {
  name: 'CourseVideo',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      uploader: null,
      // 图片上传后的地址，用于视频上传请求
      imageURL: '',
      lessonId: null,
      videoId: null,
      // 上传百分比
      uploadPercent: 0,
      isUploadSuccess: false,
      isTransCodeSuccess: false
    }
  },
  methods: {
    handleUpload () {
      // 点击上传，重置
      this.uploadPercent = 0
      this.isTransCodeSuccess = false
      this.isUploadSuccess = false
      console.log('上传')
      const videoFile = this.$refs['video-file'].files[0]
      const imgFile = this.$refs['img-file'].files[0]
      // 将要上传的文件添加到上传列表中
      this.uploader.addFile(imgFile)
      this.uploader.addFile(videoFile)
      // 开始上传
      this.uploader.startUpload()
    },
    initUploader () {
      this.uploader = new window.AliyunUpload.Vod({
        // userID，必填，只需有值即可。
        userId: '1618139964448548',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async uploadInfo => {
          let uploadAddressAndAuth = null
          console.log('执行了')
          console.log(uploadInfo)
          if (uploadInfo.isImage) {
            // 图片处理
            console.log('执行图片处理')
            const { data } = await aliyunImagUploadAddressAdnAuth()
            console.log('执行图片处理wanxheng')
            if (data.code === '000000') {
              uploadAddressAndAuth = data.data
              this.imageURL = uploadAddressAndAuth.imageURL
            }
            console.log('uploadInfo', uploadInfo)
          } else {
            // 视频处理
            console.log('执行视频处理')
            const { data } = await aliyunVideoUploadAddressAdnAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageURL
            })
            if (data.code === '000000') {
              uploadAddressAndAuth = data.data
              this.videoId = data.data.videoId
            }
          }
          // 设置凭证与地址
          console.log(uploadAddressAndAuth)
          this.uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAddressAndAuth.uploadAuth,
            uploadAddressAndAuth.uploadAddress,
            uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
          )
          // 此步设置完毕，上传进度开始执行
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
          if (!uploadInfo.isImage) {
            this.uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        // 上传凭证或STS token超时
        onUploadTokenExpired: function (uploadInfo) {
        },
        // 全部文件上传结束
        onUploadEnd: async uploadInfo => {
          this.isUploadSuccess = true
          // 发送短视频转码请求
          const { data } = await aliyunTransCode({
            lessonId: this.lessonId,
            coverImageUrl: this.imageURL,
            fileId: this.videoId,
            fileName: this.$refs['video-file'].files[0].name
          })
          if (data.code === '000000') {
            // 重复查询
            var timer = setInterval(async () => {
              const { data } = await aliyunTransCodePercent(this.lessonId)
              console.log(data)
              if (data.data === 100) {
                this.$message.success('视频转码成功')
                this.isTransCodeSuccess = true
                clearInterval(timer)
              }
            }, 1000);
          }
        }
      });
    }
  },
  created () {
    this.initUploader()
    this.lessonId = this.$route.query.lessonId
  }
}
</script>

<style>

</style>
